<?php
/**
 * database controller class
 *
 * @author raphael seebacher <raphasee@ee.ethz.ch>
 * @version 0.01
 */
class db_controller extends controller {
    protected static $instance = NULL;
    protected static $db = NULL;

    private function __construct() {
        $this->init();
    }

    public static function get_instance() {
        if (self::$instance == NULL) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    protected function init() {
        $db_specs = config::get('database');
        $this->connect($db_specs['host'],
                       $db_specs['name'],
                       $db_specs['user'],
                       $db_specs['password']);
    }

    protected function connect($host, $name, $user, $password) {
        if (($this->db = mysql_connect($host, $user, $password))
            && (mysql_select_db($name, $this->db))
        ) {
            return true;
        }
        else {
            return false;
        }
    }

    protected function disconnect() {
        if ($this->db != NULL) {
            mysql_close($this->db);
        }
    }

    public function query($q) {
        return mysql_query($q, $this->db);
    }

    public function query_assoc($q) {
        $data = $this->query($q);

        if ($data === NULL) {
            return NULL;
        }
        else if (is_bool($data)) {
            return $data;
        }

        $result = Array();
        while ($r = mysql_fetch_assoc($data)) {
            $result[] = $r;
        }

        mysql_free_result($data);

        return $result;
    }

    public function get_insert_id() {
        return mysql_insert_id($this->db);
    }

    public function escape($str) {
        return mysql_real_escape_string($str, $this->db);
    }
}
?>